<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" class="formBox formBox1 searchForm"
      label-width="68px" size="small">
      <el-form-item clearable label="医院" prop="hospital">
        <department ref="department" :isHospital="true" :isdepat="true" deptWidth="160px" @refreshData="refreshData">
        </department>
      </el-form-item>
      <el-form-item label="顾客ID" prop="patientId">
        <el-input v-model="queryParams.patientId" clearable placeholder="顾客ID" style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="顾客编号" prop="visitNum">
        <el-input v-model="queryParams.visitNum" clearable placeholder="顾客编号" style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" clearable placeholder="顾客姓名" style="width: 135px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="patientPhone">
        <el-input v-model="queryParams.patientPhone" clearable placeholder="顾客手机号" style="width: 135px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNum">
        <el-input v-model="queryParams.idNum" clearable placeholder="顾客身份证号" style="width: 200px" @focus="getSFZToSearch"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable filterable placeholder="诊断状态" style="width: 135px">
          <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="登记日期">
        <el-date-picker v-model="dateRange" :picker-options="pickerOptions" end-placeholder="结束日期" range-separator="-"
          start-placeholder="开始日期" style="width: 240px" type="daterange" value-format="yyyy-MM-dd"
          @change="handleQuery"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>

    <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-hasPermi="['patientRegistration:registrationList:add']" icon="el-icon-plus" plain size="mini"
            type="primary" @click="handleAdd">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['patientRegistration:registrationList:edit']" :disabled="single" icon="el-icon-edit"
            plain size="mini" type="success" @click="handleUpdate">修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-hasPermi="['patientRegistration:registrationList:remove']" :disabled="multiple"
            icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete">删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getPatientList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="patientList" border style="width: 100%" ref="table" class="elTable"
        @selection-change="handleSelectionChange" :height="statisticalTableH">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" label="序号" type="index" width="60">
          <template slot-scope="scope">
            <span>{{ getIndex(scope.$index) }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="顾客ID" prop="patientId" sortable width="70" />
        <el-table-column align="center" label="顾客编号" prop="visitNum" sortable width="140">
          <template slot-scope="scope">
            <el-tooltip effect="light" placement="right">
              <div slot="content" style="max-width: 700px" v-html="renderTooltip(scope.row)" />
              <span style="text-decoration: underline; color: #10a1df">
                {{ scope.row.visitNum }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="顾客姓名" prop="patientName" sortable
          width="90" />
        <el-table-column align="center" label="性别" prop="sex" sortable width="58">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="年龄" prop="age" sortable width="58">
          <!-- <template slot-scope="scope">
            <span>{{
              parseInt(
                (new Date() - new Date(parseTime(scope.row.birthDate))) /
                (1000 * 60 * 60 * 24 * 365)
              )
            }}</span>
          </template> -->
        </el-table-column>

        <el-table-column :show-overflow-tooltip="true" align="center" label="状态" prop="status" sortable width="86">
          <!--          <template slot-scope="scope">-->
          <!--            <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />-->
          <!--          </template>-->
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == '0'" type="danger" size="mini">
              <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
            </el-tag>
            <el-tag v-else-if="scope.row.status == '1'" type="warning" size="mini">
              <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
            </el-tag>
            <el-tag v-else-if="scope.row.status == '3'" type="success" size="mini">
              <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
            </el-tag>
            <el-tag v-else-if="scope.row.status == '4'" size="mini">
              <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="医生诊断" prop="doctorDiagnosis" sortable
          width="140" />
        <el-table-column :show-overflow-tooltip="true" align="center" label="医生方案" prop="doctorPlan" sortable
          width="140" />
        <el-table-column align="center" label="照片" prop="photoCount" sortable width="58">
          <template slot-scope="scope">
            <el-tag size='mini' :type="parseInt(scope.row.photoCount) > 0 ? 'primary' : 'danger'">{{
              scope.row.photoCount
            }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="就诊门诊" prop="deptName" sortable width="140" />
        <el-table-column :show-overflow-tooltip="true" align="center" label="治疗费用" prop="consultationTotalExpenses"
          sortable width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.doctorTreatmentExpenses && scope.row.doctorTreatmentExpenses != '0.00'"
              style="color:red;font-weight: 700;">
              ￥{{ formatValue(scope.row.doctorTreatmentExpenses) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="诊断方案费用" prop="consultationTotalExpenses"
          sortable width="140">
          <template slot-scope="scope">
            <div v-if="scope.row.doctorTotalExpenses && scope.row.doctorTotalExpenses != '0.00'"
              style="color:red;font-weight: 700;">
              ￥{{ formatValue(scope.row.doctorTotalExpenses) }}
            </div>
          </template>
        </el-table-column>


        <el-table-column :show-overflow-tooltip="true" align="center" label="卡号" prop="cardNumber" sortable width="120" />

        <el-table-column align="center" label="顾客性质" prop="properties" sortable width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_patient_properties" :value="scope.row.properties" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="顾客分类" prop="customerSort" sortable width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_patient_sort" :value="scope.row.customerSort" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="通用问卷" prop="questionnaireStatus" sortable width="100px">
          <template slot-scope="scope">
            <el-tag size="mini" :type="scope.row.questionnaireStatus == '1' ? 'danger' : 'primary'
              ">
              <dict-tag :options="dict.type.sys_general_questionnaire" :value="scope.row.questionnaireStatus" />
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column :show-overflow-tooltip="true" align="center" label="登记人" prop="createBy" sortable width="100" />

        <el-table-column align="center" label="登记日期" prop="createTime" sortable width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="诊断" align="center" prop="diagnosis" />
        <el-table-column sortable label="咨询医生" align="center" prop="consultants" width="100" />
        <el-table-column sortable label="咨询日期" align="center" prop="consultationDate" width="180">
        </el-table-column>
        <el-table-column sortable label="诊断医生" align="center" prop="doctorName" width="100" />
        <el-table-column sortable label="诊断日期" align="center" prop="firstVisitDate" width="180">
        </el-table-column>
        <el-table-column sortable label="知情同意书" align="center" prop="consent" width="180" />
        <el-table-column sortable label="确费" align="center" prop="confirmPrice" :show-overflow-tooltip="true" />
        <el-table-column sortable label="治疗方案" align="center" prop="treatmentPrograms" :show-overflow-tooltip="true"
          width="100" />
        <el-table-column sortable label="治疗次数" align="center" prop="numberOfTreatments" width="100" />
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" /> -->
        <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="270">
          <template slot-scope="scope">
            <el-button v-if="scope.row.questionnaireStatus == '1'" v-hasPermi="[
              'patientRegistration:registrationList:generalQuestionnaire',
            ]" :disabled="Number(scope.row.status) >= 3" icon="el-icon-document" size="mini" type="text"
              @click="openQuestionnaire(scope.row)">诊前问卷
            </el-button>
            <el-button v-else v-hasPermi="[
              'patientRegistration:registrationList:generalQuestionnaire',
            ]" :disabled="Number(scope.row.status) >= 3" icon="el-icon-document" size="mini" type="text"
              @click="updateQuestionnaire(scope.row)">修改问卷
            </el-button>
            <el-button v-hasPermi="['patientRegistration:registrationList:photo']" icon="el-icon-camera" size="mini"
              type="text" @click="goPhotoList(scope.row)">拍照
            </el-button>
            <el-button v-hasPermi="['patientRegistration:registrationList:detail']" icon="el-icon-user" size="mini"
              type="text" @click="goDetail(scope.row)">详情
            </el-button>
            <el-button v-hasPermi="['patientRegistration:registrationList:code']" icon="el-icon-menu" size="mini"
              type="text" @click="openCode(scope.row)">识别码
            </el-button>
            <el-button v-hasPermi="['patientRegistration:registrationList:id']" icon="el-icon-menu" size="mini"
              type="text" @click="editID(scope.row)">修改身份证号
            </el-button>
            <el-button v-if="Number(scope.row.status) >= 4" v-hasPermi="['patientRegistration:registrationList:id']"
              icon="el-icon-menu" size="mini" type="text" @click="editDataRecovery(scope.row)">申请修复数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
        @pagination="getPatientList" />
    </div>

    <!-- 添加或修改顾客信息对话框 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false" :title="title"
      :visible.sync="open" :width="device !== 'mobile' ? '650px' : '100%'" append-to-body class="nopaddingDailog">
      <el-form ref="baseInfoForm" :inline="true" :model="baseInfo" :rules="baseInfoFormRules" label-position="left"
        label-width="80px">
        <div class="dialogTitle">
          <img :src="require('@/assets/images/dialogTitle.png')" alt="" class="image" />
          <span class="name">基本信息</span>
        </div>
        <el-form-item label="身份证号" :prop="isIdNum ? 'idNum' : ''">
          <!--        <el-form-item label="身份证号" prop="idNum">-->
          <el-input ref="saveTagInput" v-model="baseInfo.idNum" :disabled="baseInfoInput" placeholder="请输入身份证号"
            style="width: 202px" @blur="changeBirthDate(baseInfo.idNum)" @focus="getSFZ">
            <!--             @focus="getSFZ" -->
            <i slot="suffix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-button v-if="!baseInfoInput" :disabled="baseInfoInput" plain type="danger" @click="confirmIsIdNum">{{
          isIdNum ? "无身份证号时请点击" : "有身份证号时请点击"
        }}
        </el-button>
        <el-button v-else disabled plain type="danger" @click="confirmIsIdNum">无身份证号时请点击
        </el-button>
        <el-row>
          <el-form-item label="姓名" prop="patientName">
            <el-input v-model="baseInfo.patientName" placeholder="请输入姓名" style="width: 202px"
              @blur="blurPatientName(baseInfo.patientName)">
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-form-item>
        </el-row>

        <el-form-item label="卡号" prop="cardNumber">
          <el-input v-model="baseInfo.cardNumber" placeholder="就诊卡号" style="width: 202px"
            @blur="blurCardNumber(baseInfo.cardNumber)">
            <i slot="suffix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="baseInfo.sex" clearable placeholder="性别" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthDate">
          <el-date-picker v-model="baseInfo.birthDate" placeholder="选择出生年月" style="width: 202px"
            :picker-options="expireTimeOPtion" type="date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号" prop="patientPhone">
          <el-input v-model="baseInfo.patientPhone" :maxlength="11" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="来源" prop="dataSource">
          <el-select v-model="baseInfo.dataSource" filterable clearable placeholder="选择来源" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_source_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>

        </el-form-item>
        <el-form-item label="职业" prop="job">
          <el-select v-model="baseInfo.job" filterable clearable placeholder="选择职业" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_career_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item :prop="isSFZ ? 'area' : ''" label="患者地址">
          <el-cascader v-model="baseInfo.area" :clearable="true" :options="areaList"
            :props="{ children: 'childrenList', value: 'id', label: 'name' }" class="picker-form" filterable
            placeholder="省,市,区" style="width: 496px">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="baseInfo.address" placeholder="小区/乡村名称" style="width: 496px"></el-input>
        </el-form-item>

        <el-form-item label="微信号" prop="wxNum">
          <el-input v-model="baseInfo.wxNum" placeholder="微信小程序登录后自动获取"></el-input>
        </el-form-item>
        <el-form-item label="是否拍VISIA" label-width="100px">
          <el-radio-group v-model="baseInfo.isNeedVisi">
            <el-radio label="0">不需要</el-radio>
            <el-radio label="1">需要</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="dialogTitle">
          <img :src="require('@/assets/images/dialogTitle.png')" alt="" class="image" />
          <span class="name">医疗信息</span>
        </div>
        <el-form-item label="顾客性质" prop="properties">
          <el-select v-model="baseInfo.properties" clearable placeholder="请选择顾客性质" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_patient_properties" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="皮肤色度" prop="tone">
          <el-select v-model="baseInfo.tone" clearable placeholder="请选择皮肤色度" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_skin_tone" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="顾客分类" prop="customerSort">
          <el-select v-model="baseInfo.customerSort" clearable placeholder="请选择顾客分类" style="width: 202px">
            <el-option v-for="dict in dict.type.sys_patient_sort" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="formItemRed" label="就诊门诊" prop="deptId">
          <!--          <treeselect v-model="baseInfo.deptId" :options="deptOptions" :show-count="true" placeholder="请选择就诊门诊" style="width: 202px" />-->
          <treeselect v-model="baseInfo.deptId" :defaultExpandLevel="Infinity" :disable-branch-nodes="true"
            :normalizer="normalizer" :disabled='isCurrentDeptId' :options="deptOptions" placeholder="请选择就诊门诊" style="width: 202px" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="baseInfo.remark" placeholder="请输入内容" style="width: 496px" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择顾客 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :visible.sync="patientVisible" :width="device !== 'mobile' ? '40%' : '100%'" class="nopaddingDailog" title="选择顾客">
      <div class="formBox">
        <el-table :data="patientVisibleList" border style="width: 100%">
          <el-table-column :show-overflow-tooltip="true" align="center" label="顾客姓名" prop="patientName" sortable />
          <el-table-column :show-overflow-tooltip="true" align="center" label="顾客手机号" prop="patientPhone" sortable />
          <el-table-column align="center" label="性别" prop="sex" sortable>
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="年龄" prop="birthDateCopy" sortable width="80" />
          <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button icon="el-icon-caret-right" size="mini" type="text" @click="confirmIdNum(scope.row)">点击选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 修改身份证号-->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :visible.sync="IDDialog" :width="device !== 'mobile' ? '400px' : '100%'" class="nopaddingDailog" title="修改身份证号">
      <el-form ref="IDForm" :model="IDForm" :rules="IDRules" label-position="left" label-width="100px">
        <el-form-item label="身份证号" prop="idNum">
          <el-input v-model="IDForm.idNum" placeholder="请输入身份证号" style="width: 202px">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitIDForm">提 交</el-button>
        <el-button @click="IDDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 诊前问卷 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :title="questionnaireTitle" :visible.sync="questionnaireDialog" :width="device !== 'mobile' ? '90%' : '100%'"
      class="nopaddingDailog">
      <formpreview v-if="formpreviewContList != null" ref="formPreview" :formPreviewList="formpreviewContList"
        :questionFormInfo="questionFormInfo" />
      <div slot="footer" class="dialog-footer">
        <el-button v-if="dialogNewAddBtnStatus === true" @click="submitAnswer">提 交
        </el-button>
        <el-button v-else @click="updateFormAnswer">修 改</el-button>
        <el-button @click="questionnaireDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 删除原因-->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :title="deleteTitle" :visible.sync="deleteDialog" :width="device !== 'mobile' ? '400px' : '90%'"
      class="nopaddingDailog">
      <el-form ref="deleteForm" :model="deleteForm" :rules="deleteRules" label-position="top" label-width="100px">
        <el-form-item :label="deleteLable" prop="delCause">
          <el-radio-group v-model="deleteForm.delCause">
            <el-radio v-for="dict in dict.type.sys_patient_reason" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteReason">确 定</el-button>
        <el-button @click="deleteDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增确认-->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false" :show-close="false"
      :visible.sync="confirmDialog" :width="device !== 'mobile' ? '400px' : '100%'" class="nopaddingDailog" title="新增提示">
      <div>
        该顾客登记于<span class="confirmBox">
          {{ parseTime(baseInfo.createTime) }}</span>
      </div>
      <div>
        就诊门诊:<span class="confirmBox">{{ baseInfo.deptName }}</span>
      </div>
      <div>
        当前状态为:
        <dict-tag :options="dict.type.sys_diagnosis_status" :value="baseInfo.status" class="confirmBox" />
      </div>
      <div v-if="deptOptionsStatus" style="font-size: 16px; margin-top: 10px">
        <div v-if="baseInfo.status != '3'">本次登记是想登记一个新门诊?</div>
        <div v-else>本次登记是想登记一个新门诊?还是老门诊复诊?</div>
      </div>
      <div v-else style="font-size: 16px; margin-top: 10px">
        <div v-if="baseInfo.status == '4'">本次登记是想登记一个新门诊?</div>
        <div v-if="baseInfo.status == '3'">是否为复诊?</div>
        <div v-if="baseInfo.status == '0' || baseInfo.status == '1'">
          您不需要重新登记。
        </div>
      </div>
      <div v-if="deptOptionsStatus" slot="footer" class="dialog-footer">
        <el-button @click="confirmDialog = false">登记新门诊</el-button>
        <el-button v-if="baseInfo.status != '3'" @click="closeDialog">否
        </el-button>
        <el-button v-else @click="uploadReview">复诊</el-button>
      </div>
      <div v-else slot="footer" class="dialog-footer">
        <el-button v-if="baseInfo.status == '0' || baseInfo.status == '1'" @click="closeDialog">我已知晓
        </el-button>
        <el-button v-if="baseInfo.status == '3'" @click="uploadReview">复诊
        </el-button>
        <el-button v-if="baseInfo.status == '4'" @click="confirmDialog = false">登记新门诊
        </el-button>
        <el-button v-if="baseInfo.status == '3' || baseInfo.status == '4'" @click="closeDialog">否
        </el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :title="detailTitle" :visible.sync="detailDialogVisible" :width="device !== 'mobile' ? '85%' : '100%'" center
      class="nopaddingDailog" @closed="getPatientList">
      <CustomerDetails v-if="detailDialogVisible" :basicInfo="basicInfo"></CustomerDetails>
    </el-dialog>
    <!-- 照片上传 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :visible.sync="pictureDatileopen" :width="device !== 'mobile' ? '95%' : '100%'" append-to-body
      class="nopaddingDailog" title="照片上传">
      <photoUpload v-if="pictureDatileopen" :isMorePic="false" :patientItem="patientItem" isPosition="1"
        @closepictureDatile="refreshList()"></photoUpload>
    </el-dialog>
    <!-- 识别码 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :visible.sync="codeDialogVisible" :width="device !== 'mobile' ? '420px' : '100%'" append-to-body
      class="nopaddingDailog" title="识别码">
      <recognizeCode v-if="codeDialogVisible" :patientItem="patientItem"></recognizeCode>
    </el-dialog>
    <!-- 数据修复 -->
    <el-dialog v-dialogDrag :class="device !== 'mobile' ? '' : 'active'" :close-on-click-modal="false"
      :visible.sync="dataRecoveryDialogVisible" :width="device !== 'mobile' ? '900px' : '100%'" append-to-body
      class="nopaddingDailog" title="数据修复申请">
      <dataRecovery v-if="dataRecoveryDialogVisible" :patientItem="patientItem"
        @closeDataRecovery="dataRecoveryDialogVisible = false"></dataRecovery>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { mapGetters } from "vuex";
import {
  addVisit,
  deleteVisit,
  getDetailVisit,
  listVisitTip,
  getVisitStatus,
  updateVisit,
  getQuestionnaireCommon,
} from "@/api/patientRegistration/registrationList";
import photoUpload from "@/views/components/uploadImage/photoUpload.vue";
import { addressJson } from "@/api/patients/personal";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import recognizeCode from "@/views/components/recognizeCode";
import dataRecovery from "@/views/components/dataRecovery";
import {
  listFormCont,
  addFormAnswer,
  listAnswer,
  updateAnswer,
  currencyFormId,
  detailFormAndAnswer,
} from "@/api/system/form";
import Formpreview from "@/views/system/form/Formpreview";
import CustomerDetails from "@/views/components/customerDetail/customerDetail";
import department from "@/views/components/department/index.vue";
import { startReadCard } from "@/utils/getIdCard";
import { uploadReview } from "@/api/patientReview/review";
import { listDept } from "@/api/system/dept";
//自定义校验规则
var checkIdCard = (rule, value, cb) => {
  const regIdCard =
    /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if (regIdCard.test(value)) {
    return cb();
  }
  cb(new Error("您输入的身份证号码不是有效格式"));
};
var checkPatientPhone = (rule, value, cb) => {
  const regPatientPhone = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (regPatientPhone.test(value)) {
    return cb();
  }
  cb(new Error("您输入的手机号码不是有效格式"));
};

export default {
  name: "Registration",
  dicts: [
    "sys_diagnosis_status",
    "sys_user_sex",
    "sys_patient_properties",
    "sys_skin_tone",
    "sys_patient_sort",
    "sys_outpatient_clinic",
    "sys_general_questionnaire",
    "sys_patient_reason",
    "sys_source_type",
    "sys_career_type",
  ],
  components: {
    Treeselect,
    Formpreview,
    CustomerDetails,
    department,
    photoUpload,
    recognizeCode,
    dataRecovery,
  },

  data() {
    return {
      expireTimeOPtion: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              const end = date;
              const start = date;
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "前天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
              const end = date;
              const start = date;
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近1年",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      isCurrentDeptId:false,
      pictureDatileopen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      patientNames: [],
      patientItem: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 登记顾客列表
      patientList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientId: undefined,
        visitNum: undefined,
        patientName: undefined,
        patientPhone: undefined,
        idNum: undefined,
        status: undefined,
      },
      // 新增顾客信息

      // 弹出层标题
      title: "",
      // 科室树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 科室名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 顾客信息
      baseInfo: {
        address: undefined,
        area: undefined,
        birthDate: undefined,
        cardNumber: undefined,
        cityId: undefined,
        countyId: undefined,
        customerSort: undefined,
        deptId: undefined, // deptId: 0,
        hospitalId: undefined,
        diagnosis: undefined,
        doctorId: undefined,
        doctorTime: undefined, //"2023-03-09T11:42:21.539Z"
        idNum: undefined,
        job: undefined,
        patientId: undefined,
        patientName: undefined,
        patientPhone: undefined,
        properties: "0",
        provinceId: undefined,
        questionnaireStatus: undefined,
        referee: undefined,
        refereeTime: undefined, //2023-03-09T11:42:21.539Z
        remark: undefined,
        sex: undefined,
        status: undefined,
        tone: undefined,
        visitId: undefined,
        visitNum: undefined,
        wxNum: undefined,
        isNeedVisi: undefined,
        dataSource:undefined,
      },
      // 省市区
      areaList: [],
      //是否有身份证号
      isIdNum: true,
      // 表单校验
      baseInfoFormRules: {
        idNum: [
          {
            required: true,
            message: "身份证号不能为空",
            trigger: "blur",
          },
          { validator: checkIdCard, trigger: "blur" },
        ],
        patientName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
            trigger: "blur",
          },
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不能为空",
            trigger: "blur",
          },
        ],
        patientPhone: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          { validator: checkPatientPhone, trigger: "blur" },
        ],
        properties: [
          {
            required: true,
            message: "顾客性质不能为空",
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: "就诊科室不能为空",
            trigger: "blur",
          },
        ],
      },
      // 禁止修改
      baseInfoInput: false,

      // 诊前问卷弹出层标题
      questionnaireTitle: "",
      // 诊前问卷弹出层是否显示
      questionnaireDialog: false,
      // 诊前问卷表单
      questionnaireForm: {
        name: "",
        region: "",
        type: "",
      },
      questionnaireRules: {
        name: [
          {
            required: true,
            message: "未勾选",
            trigger: "blur",
          },
        ],
      },
      deleteForm: {
        delCause: "",
      },
      deleteRules: {
        delCause: [
          {
            required: true,
            message: "未勾选",
            trigger: "blur",
          },
        ],
      },
      formpreviewContList: null,
      formInfo: {},
      questionFormInfo: {
        name: "",
        remark: "",
      },
      // 删除原因弹出框
      deleteDialog: false,
      deleteTitle: "",
      deleteLable: "",
      // 确认新增弹出框
      confirmDialog: false,
      confirmTitle: "",
      dialogNewAddBtnStatus: "", //诊前问卷弹窗新增或者修改状态
      myAnswer: null, //存放表单答案
      detailTitle: "",
      detailDialogVisible: false,
      basicInfo: {},
      searchDeptId: "",
      deptOptionsStatus: true,
      visitIdStatus: false,
      isSFZ: true,
      deptOptionsArr: [],
      waitConsultationList: [],
      codeDialogVisible: false,
      // 顾客选择弹窗
      patientVisible: false,
      patientVisibleList: [],
      confirmIdNumShow: false,
      IDDialog: false,
      IDForm: {},
      statisticalTableH: undefined,
      dataRecoveryDialogVisible: false,
      IDRules: {
        idNum: [
          {
            required: true,
            message: "身份证号不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选科室树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    showSearch() {
      console.log("执行----****")
      this.$nextTick(() => {
        this.changeHeight()
      }, 1000)

    }

  },
  async created() {
    this.dateRange = this.defaultTime;
    this.getAddressData();
    this.getDeptTree();
    console.log("this.dict", this.dict);
  },
  computed: {
    ...mapGetters(["dept", "hospital", "device"]),
    defaultTime: function () {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month > 9 ? month : "0" + month;
      day = day < 10 ? "0" + day : day;
      let today = year + "-" + month + "-" + day;
      return [today, today];
    },
  },
  mounted() {
    this.changeHeight()
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    changeHeight() {
      if (this.$refs.statisticalTable) {
        const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
        let h = statisticalTableObj.top + 100
        this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
      } else {
        this.statisticalTableH = '500px'
      }
    },
    editDataRecovery(row) {
      this.patientItem = row;
      this.dataRecoveryDialogVisible = true;
    },
    renderTooltip(row) {
      return `<div style="margin-bottom:5px;font-size:20px;color:#1890ff;"><span style="font-weight:bold;"> 顾客状态：</span>${this.matchDict(
        "sys_diagnosis_status",
        row.status
      )}</div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">登记日期：</span>${this.parseTime(
        row.createTime
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">登记人：</span>${this.formatValue(
        row.createBy
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">就诊科室：</span>${this.formatValue(
        row.deptName
      )}</span> </div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">顾客性质：</span>${this.matchDict(
        "sys_patient_properties",
        row.properties
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">顾客分类：</span>${this.matchDict(
        "sys_patient_sort",
        row.customerSort
      )}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">地址：</span>${this.formatValue(
        row.address
      )}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">电话：</span>${this.formatValue(
        row.patientPhone
      )}</div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">通用问卷：</span>${this.matchDict(
        "sys_general_questionnaire",
        row.questionnaireStatus
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">专病问卷：</span>${this.formatValue(
        row.diseaseQuestionnaireStatus
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">照片：</span>${this.formatValue(
        row.photoCount
      )}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">咨询日期：</span>${this.formatValue(
        row.consultationTime
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">咨询医生：</span>${this.formatValue(
        row.consultationer
      )}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">咨询诊断：</span>${this.formatValue(
        row.consultationDiagnosis
      )}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">咨询方案：</span>${this.formatValue(
        row.consultationPlan
      )}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">方案总额：</span>${this.formatValue(
        row.consultationTotalExpenses
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗费用：</span>${this.formatValue(
        row.consultationTreatmentExpenses
      )}</span></div>
      <div style="width: 100%;height:1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">诊断日期：</span>${this.formatValue(
        row.doctorTime
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">诊断医生：</span>${this.formatValue(
        row.doctor
      )}</span></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">医生诊断：</span>${this.formatValue(
        row.doctorDiagnosis
      )}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="font-weight:bold;">医生方案：</span>${this.formatValue(
        row.doctorPlan
      )}</div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">方案总额：</span>${this.formatValue(
        row.doctorTotalExpenses
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗费用：</span>${this.formatValue(
        row.doctorTreatmentExpenses
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">复诊次数：</span>${this.formatValue(
        row.reviewNum
      )}</span></div>
      <div style="width: 100%;height: 1px;background-color: red;margin-bottom:5px;"></div>
      <div style="margin-bottom:5px;font-size:18px"><span style="margin-right:10px;"><span style="font-weight:bold;">知情同意书：</span>${this.formatValue(
        row.informedConsent
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">确费状态：</span>${this.formatValue(
        row.confirmExpense == "1" ? "已确费" : "未确费"
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">治疗次数：</span>${this.formatValue(
        row.treatmentTimes
      )}</span><span style="margin-right:10px;"><span style="font-weight:bold;">温馨提示：</span>${this.formatValue(
        row.tipsTimes
      )}</span></div>`;
    },
    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },
    formatValue(value) {
      if (value == null) {
        return "";
      } else {
        return value;
      }
    },
    refreshData(data) {
      this.queryParams.pageNum = 1;
      this.queryParams.hospitalId = data.hospitalId;
      this.queryParams.deptId = data.deptId;
      this.getPatientList();
    },
    refreshList() {
      this.pictureDatileopen = false;
      this.handleQuery();
    },
    async getSFZ() {
      const res = await startReadCard();
      if (res.result == 3) {
        this.isSFZ = true;
        this.$message.warning("请把身份证放到读卡器上");
        // this.$refs.saveTagInput.blur();
      } else if (res.result == 2) {
        // this.$message.warning('设备不存在')
        this.isSFZ = true;
      } else {
        this.isSFZ = false;
        this.baseInfo.idNum = res.gmsfhm;
        this.baseInfo.patientName = res.xm;
        this.baseInfo.sex =
          res.xbmc == "男" ? "0" : res.xbmc == "女" ? "1" : "";
        this.baseInfo.address = res.dzmc;
        this.changeBirthDate(res.gmsfhm);
      }
    },
    async getSFZToSearch() {
      const res = await startReadCard();
      if (res.result == 3) {
        this.$message.warning("请把身份证放到读卡器上");
        // this.$refs.saveTagInput.blur();
      } else if (res.result == 2) {
        // this.$message.warning('设备不存在')
      } else {
        this.queryParams.idNum = res.gmsfhm;
      }
    },
    submitAnswer() {
      this.$nextTick(() => {
        this.$refs.formPreview.$refs.listForm.validate((valid, object) => {
          console.log(valid);
          if (valid) {
            let answerArr = [];
            const Vmodel = this.$refs.formPreview.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            this.formpreviewContList.forEach((item, index) => {
              this.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            let mData = {
              visitId: this.formInfo.visitId,
              patientId: this.formInfo.patientId,
              formId: this.formInfo.formId,
              answer: answerStr,
              formType: 0, //通用表单
            };
            addFormAnswer(1, mData).then((response) => {
              this.$message.success("提交成功");
              this.questionnaireDialog = false;
              this.getPatientList();
            });
          } else {
            this.$message({
              message: "请完善问卷之后再提交~",
              type: "warning",
            });
          }
        });
      });
    },

    // 获取地区
    getAddressData() {
      addressJson().then((res) => {
        this.areaList = res.data;
      });
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      // deptTreeSelect().then((response) => {
      //   this.deptOptions = response.data[0].children;
      //   // console.log('getDeptTree--',this.deptOptions)
      //   if(this.deptOptions.length==1){
      //     this.baseInfo.deptId = this.deptOptions[0].id
      //   }
      // });
      listDept().then((response) => {
        let data = response.data;
        this.deptOptionsArr = data;
        if (this.getSplit(this.dept.ancestors).length == 3) {
          //3级用户
          data.push(this.hospital); //默认加一个上级医院
        }
        this.deptOptions = this.handleTree(data, "deptId")[0].children;
        if (this.deptOptions.length == 1) {
          this.baseInfo.deptId = this.deptOptions[0].deptId;
          if (this.deptOptions[0].parentId != 0) {
            this.baseInfo.hospitalId = this.deptOptions[0].parentId;
          }
        } else {
          const currentDeptId = Cookies.get("currentDeptId");
          if (currentDeptId) {
            this.baseInfo.deptId = Number(currentDeptId);
            this.isCurrentDeptId=true
          } else {
            this.baseInfo.deptId = undefined;
            this.isCurrentDeptId=false
          }
        }
        // console.log('this.deptOptions ',this.deptOptions )
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    confirmIsIdNum() {
      if (this.isIdNum) {
        this.$confirm(
          `请确认该顾客无身份证?系统自动生成一个随机数,建议输入亲属身份证号加或减1位!`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then((content) => {
            this.isIdNum = false;
            this.baseInfo.idNum = "98" + Date.now();
          })
          .catch((error) => {
            return;
          });
      } else {
        this.isIdNum = true;
      }
    },
    changeBirthDate(idCard) {
      console.log("changeBirthDate--", idCard);
      if (!idCard) {
        return;
      }
      var birthday = "";
      var genderCode = ""; // 性别代码
      if (idCard != null && idCard != "") {
        // 一代身份证号码长度为15位（第15位为性别代码）
        if (idCard.length == 15) {
          birthday = "19" + idCard.substr(6, 6);
          genderCode = idCard.charAt(14);
        } else if (idCard.length == 18) {
          // 二代身份证号码长度为18位（第17位为性别代码）
          birthday = idCard.substr(6, 8);
          genderCode = idCard.charAt(16);
        }
        if (genderCode && !isNaN(genderCode)) {
          // 两代身份证号码的性别代码都为男奇女偶
          if (parseInt(genderCode) % 2 == 0) {
            this.baseInfo.sex = "1";
          } else {
            this.baseInfo.sex = "0";
          }
        }
        birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
      }
      this.baseInfo.birthDate = birthday;
      this.confirmIdNumShow = true;
      this.getVisitStatusList(idCard, 0);
    },
    confirmIdNum(row) {
      this.confirmIdNumShow = true;
      this.getVisitStatusList(row.idNum, 0);
    },
    blurPatientName(value) {
      if (!this.baseInfo.idNum) {
        if (!this.baseInfoInput) {
          this.confirmIdNumShow = false;
          this.getVisitStatusList(value, 1);
        }
      }
    },
    blurCardNumber(value) {
      if (!this.baseInfo.idNum) {
        if (!this.baseInfoInput) {
          this.confirmIdNumShow = false;
          this.getVisitStatusList(value, 2);
        }
      }
    },

    getVisitStatusList(value, type) {
      if (!value) {
        return;
      }
      getVisitStatus(value, type).then((response) => {
        if (response.code == 200) {
          this.waitConsultationList = response.data; //查出此病人所有未治疗结束的记录
          console.log("getVisitStatus", response);
          console.log("confirmIdNumShow", this.confirmIdNumShow);
          if (response.data == false) {
            let oldVisitData = response.oldVisit;
            if (!this.visitIdStatus) {
              const currentDeptId = Cookies.get("currentDeptId");
              if (currentDeptId) {
                oldVisitData.deptId = Number(currentDeptId);
                this.isCurrentDeptId=true
              } else {
                oldVisitData.deptId =undefined
                this.isCurrentDeptId=false
              }

            }
            this.baseInfo = oldVisitData;
          }
          // if (response.data.length>0&&response.data[0].idNum) {
          if (response.data.length > 0) {
            if (this.confirmIdNumShow) {
              this.confirmPatient(response.data[0]);
            } else {
              if (response.data.length == 1) {
                this.confirmPatient(response.data[0]);
              } else {
                this.patientVisible = true;
                this.patientVisibleList = response.data;
                this.patientVisibleList.forEach((item) => {
                  item.birthDateCopy = parseInt(
                    (new Date() - new Date(this.parseTime(item.birthDate))) /
                    (1000 * 60 * 60 * 24 * 365)
                  );
                });
              }
            }
          }
        }
      });
    },
    confirmPatient(value) {
      this.patientVisible = false;
      this.confirmIdNumShow = false;
      if (!this.visitIdStatus) {
        value.deptId = undefined
      }
      this.baseInfo = value;
      this.confirmDialog = true;
      console.log("this.baseInfo---", this.baseInfo);
      this.baseInfo.area = [
        Number(this.baseInfo.provinceId),
        Number(this.baseInfo.cityId),
        Number(this.baseInfo.countyId),
      ];
      this.baseInfo.questionnaireStatus = "1";
      this.baseInfoInput = true;
      this.isIdNum = false;
      //比对deptId门诊(新增逻辑部分)
      console.log("this.deptOptions----", this.deptOptions);
      this.deptOptions = this.deptOptions.filter((item) => {
        return !this.waitConsultationList.find((prop) => {
          return prop.deptId == item.deptId;
        });
      }); //从部门中过滤出此病人未结束的部门记录
      console.log("this.deptOptions++++", this.deptOptions);
      if (this.deptOptions.length > 0) {
        this.deptOptionsStatus = true;
        this.baseInfo.deptId = this.deptOptions[0].deptId;
      } else {
        this.deptOptionsStatus = false;
        const currentDeptId = Cookies.get("currentDeptId");
        if (currentDeptId) {
          this.baseInfo.deptId = Number(currentDeptId);
          this.isCurrentDeptId=true
        } else {
          this.baseInfo.deptId = undefined;
          this.isCurrentDeptId=false
        }

      }
      // console.log('this.deptOptions---', this.deptOptions)
      // if (Number(response.data[0].status) < 4) {
      //   this.searchDeptId = response.data[0].deptId
      //   if (this.deptOptions.length > 1) {
      //     this.deptOptions = this.deptOptions.filter((item) => {
      //       return item.deptId != this.searchDeptId
      //     })
      //     this.deptOptionsStatus = true
      //     this.baseInfo.deptId = this.deptOptions[0].deptId
      //     console.log('this.deptOptions---', this.deptOptions)
      //   } else {
      //     this.deptOptionsStatus = false
      //   }
      // }
    },
    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },

    // 获取顾客登记列表
    getPatientList() {
      this.loading = true;
      if (this.queryParams.visitNum || this.queryParams.patientId) {
        this.dateRange = [];
      }

      listVisitTip(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.patientList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.isSFZ = true;
      this.baseInfo = {
        address: undefined,
        area: undefined,
        birthDate: undefined,
        cardNumber: undefined,
        cityId: undefined,
        countyId: undefined,
        customerSort: undefined,
        deptId: undefined, // deptId: 0,
        hospitalId: undefined,
        diagnosis: undefined,
        doctorId: undefined,
        doctorTime: undefined, //"2023-03-09T11:42:21.539Z"
        idNum: undefined,
        job: undefined,
        patientId: undefined,
        patientName: undefined,
        patientPhone: undefined,
        properties: "0",
        provinceId: undefined,
        questionnaireStatus: undefined,
        referee: undefined,
        refereeTime: undefined, //2023-03-09T11:42:21.539Z
        remark: undefined,
        sex: undefined,
        status: undefined,
        tone: undefined,
        visitId: undefined,
        visitNum: undefined,
        wxNum: undefined,
        isNeedVisi: undefined,
        dataSource:undefined,
      };
      this.resetForm("baseInfoForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPatientList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.baseInfoInput = false;
      this.open = true;
      this.title = "新增顾客";
      this.visitIdStatus = false;
      this.isIdNum = true;
      this.baseInfo.isNeedVisi = "0";

      this.getDeptTree();
      if (this.patientItem.length > 0) {
        console.log("----------");
        this.baseInfo.idNum = this.patientItem[0].idNum;
        this.changeBirthDate(this.baseInfo.idNum);
        this.baseInfoInput = true;
        this.isIdNum = false;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.visitId);
      this.patientNames = selection.map((item) => item.patientName);
      this.patientItem = selection.map((item) => item);

      console.log("this.patientItem", this.patientItem);
      this.single = selection.length != 1;
      this.multiple = selection.length != 1;
      // this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getDeptTree();
      this.visitIdStatus = true;
      this.isIdNum = false;
      // console.log('handleUpdate',this.patientItem)
      if (Number(this.patientItem[0].status) == 4) {
        this.$confirm(`该顾客治疗结束,无法修改基本信息!`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then((content) => {
            return;
          })
          .catch((error) => {
            return;
          });
      } else {
        this.reset();
        this.baseInfoInput = true;
        const visitId = row.visitId || this.ids;
        getDetailVisit(visitId).then((response) => {
          this.baseInfo = response.data;
          this.baseInfo.area = [
            Number(response.data.provinceId),
            Number(response.data.cityId),
            Number(response.data.countyId),
          ];
          this.open = true;
          this.title = "修改顾客";
          // console.log('getDetailVisit', this.baseInfo)
        });
      }
    },
    getSplit(str) {
      return str.split(",");
    },
    selectable(time) {
      var strtime = time.replace("/-/g", "/"); //时间转换
      var date1 = new Date(strtime); //现在时间
      var date2 = new Date();
      var d2 =
        date2.getFullYear() +
        "/" +
        (date2.getMonth() + 1) +
        "/" +
        date2.getDate();
      var date3 = new Date(d2);
      //判断时间是否有效
      return date1 > date3 ? true : false;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["baseInfoForm"].validate((valid) => {
        if (!!this.baseInfo.area) {
          this.baseInfo.provinceId = String(this.baseInfo.area[0]);
          this.baseInfo.cityId = String(this.baseInfo.area[1]);
          this.baseInfo.countyId = String(this.baseInfo.area[2]);
        }
        let deptOptionsArr = this.deptOptionsArr;
        // deptId: undefined, // deptId: 0,
        // hospitalId:undefined,

        // console.log("this.baseInfo.visitId", this.baseInfo.visitId);
        if (valid) {
          let that = this;

          deptOptionsArr.forEach(function (ele) {
            console.log(ele.deptId);
            if (ele.deptId == that.baseInfo.deptId) {
              console.log(ele);
              console.log("___专病————");
              if (
                that.getSplit(ele.ancestors).length != 2 &&
                that.getSplit(ele.ancestors).length != 1
              ) {
                that.baseInfo.hospitalId = ele.parentId;
              } else {
                that.baseInfo.hospitalId = ele.deptId;
              }
            }
          });
          // 判断以下日期是否有效
          if (this.baseInfo.birthDate) {
            if (this.selectable(this.baseInfo.birthDate)) {
              console.log(this.selectable(this.baseInfo.birthDate));
              this.$message.warning("请检查身份证信息或者生日日期");
              return false;
            }
          }

          if (this.visitIdStatus) {
            console.log("this.baseInfo--updateVisit", this.baseInfo);
            updateVisit(this.baseInfo).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getPatientList();
              }
            });
          } else {
            this.baseInfo.status = "0";
            this.baseInfo.visitNum = null;
            delete this.baseInfo.visitId;
            console.log("this.baseInfo--addVisit", this.baseInfo);
            addVisit(this.baseInfo).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getPatientList();
              }
            });
          }
        }
      });
    },
    /** 诊前问卷按钮操作 */
    async openQuestionnaire(row) {
      this.formInfo = row;
      // let hospitalId;
      // if (this.hospital.ancestors == "0") {
      //   hospitalId = "";
      // } else {
      //   hospitalId = this.hospital.deptId;
      // }

      currencyFormId({ deptId: row.deptId }).then((res) => {
        if (res.code == 200) {
          this.formInfo.formId = res.data;
          if (res.data) {
            this.getFormContList();
          }
          this.dialogNewAddBtnStatus = true;
          this.questionnaireTitle = "新增顾客通用诊前问卷";
        }
      });
    },
    /** 修改诊前问卷按钮操作 */
    updateQuestionnaire(row) {
      this.dialogNewAddBtnStatus = false;
      getQuestionnaireCommon(row.visitId).then((response) => {
        const visitLogId = response.data[0].visitLogId;
        console.log("点击修改按钮获取的答案和表单列表", this.myAnswer);
        detailFormAndAnswer(visitLogId).then((response) => {
          this.formInfo = response.data;
          this.myAnswer = JSON.parse(response.data.answer);
          this.getFormContList();
        });
      });
      this.questionnaireTitle = "修改顾客通用诊前问卷";
    },
    /** 修改诊前问卷按钮操作 */
    async updateFormAnswer() {
      this.$nextTick(() => {
        this.$refs.formPreview.$refs.listForm.validate((valid) => {
          if (valid) {
            let answerArr = [];
            const Vmodel = this.$refs.formPreview.$refs.listForm.model;
            Object.keys(Vmodel).forEach((item) => {
              answerArr.push({ answer: Vmodel[item], questionId: null });
            });
            this.formpreviewContList.forEach((item, index) => {
              this.$set(answerArr[index], "questionId", item.questionId);
            });
            let answerStr = JSON.stringify(answerArr);
            let mData = {
              visitLogId: this.formInfo.visitLogId,
              answer: answerStr,
            };
            updateAnswer(1, mData).then((response) => {
              if (response.code == 200) {
                this.$message.success("修改成功");
                this.questionnaireDialog = false;
              }
            });
          }
        });
      });
    },

    /** 查询表单内容控件列表 */
    getFormContList() {
      listFormCont({
        formId: this.formInfo.formId,
      }).then((response) => {
        this.questionFormInfo.name = response.name;
        this.questionFormInfo.remark = response.remark;
        this.formpreviewContList = response.rows;
        this.formpreviewContList.forEach((item, index) => {
          if (this.dialogNewAddBtnStatus === false) {
            this.$set(item, "answer", this.myAnswer[index].answer);
          } else {
            if (item.questionType === "2") {
              this.$set(item, "answer", []);
            } else {
              this.$set(item, "answer", null);
            }
          }
        });
      });
      this.questionnaireDialog = true;
    },
    /** 拍照按钮操作 */
    goPhotoList(row) {
      // const userInfo = {
      //   visitNum: row.visitNum,
      //   patientName: row.patientName,
      //   patientPhone: row.patientPhone,
      //   idNum: row.idNum,
      // };
      // this.$store.dispatch("app/changePhotoUserInfo", userInfo);
      // this.$router.push("/photoWorkstation/photoList");
      this.patientItem = row;
      this.pictureDatileopen = true;
      //this.$router.push({ path: "/photoWorkstation/index", query: { visitNum: row.visitNum } });
    },
    goDetail(row) {
      // this.$router.push("/patientRegistration/patientRegistration-detail/index/" + row.patientId);
      this.detailTitle = "顾客详情";
      this.basicInfo = row;
      this.detailDialogVisible = true;
    },
    openCode(row) {
      console.log("openCode--", row);
      this.patientItem = row;
      this.codeDialogVisible = true;
    },
    editID(row) {
      const visitId = row.visitId;
      getDetailVisit(visitId).then((response) => {
        if (response.code == 200) {
          this.IDForm = response.data;
          this.IDDialog = true;
        }
      });
    },
    submitIDForm() {
      this.$confirm("请确认修改该顾客的身份证号！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((content) => {
          updateVisit(this.IDForm).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.IDDialog = false;
              this.getPatientList();
            }
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (Number(this.patientItem[0].status) > 0) {
        this.$confirm(`该顾客不是待咨询状态,无法删除基本信息!`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true,
        })
          .then((content) => {
            return;
          })
          .catch((error) => {
            return;
          });
      } else {
        const patientNames = row.patientName || this.patientNames;
        this.deleteDialog = true;
        this.deleteTitle = "删除顾客";
        this.deleteLable =
          '确定删除"' + patientNames + '"的顾客资料吗？请选择删除原因';
      }
    },
    // 删除原因
    deleteReason() {
      // const visitIds = String(this.ids[0]);
      const visitIds = this.ids;
      const delCause = this.deleteForm.delCause;
      this.$refs["deleteForm"].validate((valid) => {
        if (valid) {
          deleteVisit(visitIds, delCause).then((response) => {
            this.$modal.msgSuccess("删除成功");
            this.deleteDialog = false;
            this.getPatientList();
          });
        }
      });
    },
    // 关闭弹窗
    closeDialog() {
      this.confirmDialog = false;
      this.open = false;
      this.getPatientList();
    },
    //复诊
    uploadReview() {
      uploadReview(this.baseInfo.visitNum).then((response) => {
        if (response.code == 200) {
          this.confirmDialog = false;
          this.open = false;
          this.getPatientList();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
/*只要设置formBox,就会有该样式,以下注释的样式已经放在全局里面了,可以不用引用该样式*/
/*.formBox {*/
/*  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.2);*/
/*  border-radius: 4px 4px 4px 4px;*/
/*  padding: 20px;*/
/*  margin-bottom: 20px;*/
/*}*/

/*.formBox .el-form-item {*/
/*  margin-bottom: 10px;*/
/*}*/

/*::v-deep .formItemRed .el-form-item__label {*/
/*  color: red;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__header {*/
/*  text-align: left;*/
/*  !*font-weight: bold;*!*/
/*  border-bottom: 1px solid #f3a4a1;*/
/*  padding-bottom: 0px;*/

/*}*/

/*::v-deep .el-dialog .el-dialog__header .el-dialog__title {*/
/*  color: #f3a4a1;*/
/*  line-height: 34px;*/
/*  display: inline-block;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__header .el-dialog__title::after {*/
/*  content: '';*/
/*  display: block;*/
/*  height: 3px;*/
/*  background-color: #f3a4a1;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__body {*/
/*  padding: 20px;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__body .dialogTitle {*/
/*  position: relative;*/
/*  margin-bottom: 20px;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__body .dialogTitle .name {*/
/*  color: #606266;*/
/*  font-weight: bold;*/
/*  font-size: 16px;*/
/*  position: absolute;*/
/*  left: 30px;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__body .dialogTitle .image {*/
/*  width: 100%;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__body .el-form-item__label {*/
/*  font-weight: normal;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__footer {*/
/*  padding-top: 0px;*/
/*}*/

/*::v-deep .el-dialog .el-dialog__footer .dialog-footer {*/
/*  text-align: center;*/
/*  !*border-top: 1px solid #f3a4a1;*!*/
/*}*/

/*::v-deep .el-dialog .dialog-footer .el-button:first-child {*/
/*  background-color: #f3a4a1;*/
/*  color: white;*/
/*}*/

/*::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before,*/
/*.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label:before {*/
/*  display: none;*/
/*}*/

/*::v-deep .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label::after,*/
/*.el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap>.el-form-item__label::after {*/
/*  content: '*';*/
/*  color: red;*/
/*  margin-left: 4px;*/
/*}*/
/*!*!*滚动条样式*!*!*/
/*!*!*胶囊背景色*!*!*/
/* ::v-deep .el-table__body-wrapper::-webkit-srollbar-track {*/
/*   background-color: rgba(255, 255, 255, 0);*/
/* }*/
/*!*可设置胶囊宽高*!*/
/*::v-deep .el-table__body-wrapper::-webkit-scrollbar {*/
/*  height: 6px;*/
/*  width: 10px;*/
/*  opacity: 0.5;*/
/*}*/
/*!*设置胶囊色*!*/
/* ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {*/
/*   border-radius: 15px;*/
/*   background-color: #c1c1c1;*/
/* }*/
/*  ::v-deep .el-table__fixed-right{*/
/*    height: 100% !important;*/
/*    bottom: 6px !important;*/
/*  }*/
/* ::v-deep .el-table__fixed-right .el-table__fixed-body-wrapper{*/
/*   height: calc(100% - 43px) !important;*/
/* }*/
::v-deep .el-dialog {
  margin-top: 0 !important;
}

.confirmBox {
  display: inline;
  font-weight: bold;
  font-size: 18px;
}
</style>
